package com.example.utils;

import sun.misc.ClassLoaderUtil;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @Classname LoadJarUtils
 * @Description TODO
 * @Date 2022/6/5 18:25
 * @Created by XiongXiong
 * @Author: X.I.O
 */
public class LoadJarUtils {

  private static URLClassLoader urlClassLoader;



  /**
   * 动态加载本地jar，初始化类加载器
   */
  public static void loadJar(String jarPath) {

    URL url = null;
    File jarFile=null;
    try {
      // 加载本地jar
       jarFile= new File(jarPath);
      // 如果不存在该文件
      if(!jarFile.exists()){
        System.out.println("指定加载的jar不存在, jarPath:" + jarPath);
        return;
      }
      url = jarFile.toURI().toURL();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }

    if(url != null){
      urlClassLoader = new URLClassLoader(new URL[]{url});
    }
  }

  /**
   * 重新加载jar
   * @param newJarPath
   */
  public static void reloadJar(String newJarPath){
    // 卸载当前jar
    unloadJar();
    // 重新加载新的jar
    loadJar(newJarPath);
  }

  /**
   * 卸载当前jar
   */
  public static void unloadJar(){
    if(urlClassLoader != null){
      // 卸载当前动态加载进来的jar
      ClassLoaderUtil.releaseLoader(urlClassLoader);
    }
  }

  /**
   * 获取当前的UrlClassLoader
   * @return
   */
  public static URLClassLoader getUrlClassLoader() {
    if (urlClassLoader == null){
      throw new RuntimeException("动态加载jar可能出现了异常，导致无法获取UrlClassLoader");
    }
    return urlClassLoader;
  }
}
